#include "logger.h"
#include <spdlog/spdlog.h>
#include <spdlog/sinks/daily_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/dist_sink.h>
#include <cstdarg>
#include <cstdio>
#include <memory>

namespace multi_sink {
    
    Logger& Logger::getInstance() {
        static Logger instance;
        return instance;
    }
    
    std::shared_ptr<Logger> Logger::createLogger(const std::string& tag) {
        auto logger = std::shared_ptr<Logger>(new Logger(tag));
        logger->init(tag);
        return logger;
    }
    
    Logger::Logger(const std::string& tag) : tag_(tag) {}
    
    int Logger::init(const std::string& tag) {
        // 如果提供了tag参数，则更新tag_
        if (!tag.empty()) {
            tag_ = tag;
        }
        
        try {
            // 创建分布式sink
            auto dist_sink = std::make_shared<spdlog::sinks::dist_sink_st>();
            
            // 创建控制台sink
            auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
            
            // 创建每日文件格式sink
            auto file_sink = std::make_shared<spdlog::sinks::daily_file_format_sink_mt>("logs/%Y-%m-%d/hourly_rotating_%H.log", 0, 0, false, 24);
            
            // 添加sinks到分布式sink
            dist_sink->add_sink(console_sink);
            dist_sink->add_sink(file_sink);
            
            // 创建logger
            logger_ = std::make_shared<spdlog::logger>(tag_, dist_sink);
            
            // 注册logger
            spdlog::register_logger(logger_);
            
            // 设置日志级别
            logger_->set_level(spdlog::level::trace);
            
            // 启用自动刷新
            logger_->flush_on(spdlog::level::trace);
            
            return 0;  // 成功
        } catch (const spdlog::spdlog_ex &ex) {
            printf("初始化多sink日志记录器失败: %s\n", ex.what());
            return -1;  // 失败
        }
    }
    
    void Logger::destroy() {
        if (logger_) {
            spdlog::drop(logger_->name());
            logger_ = nullptr;
        }
    }
    

    
} // namespace multi_sink